#include "robotcontrolform.h"
#include "MessageBox.h"
#include "mainwindow.h"
#include "telemetrydialog.h"
#include "ui_robotcontrolform.h"
#include"version.h"
#include "models/robotlist.h"

#include "passworddialog.h"
#include "usermenu.h"
#include "zerodialog.h"

#include <models/curusermodel.h>
#include "models/operatelogmodel.h"
#include "urdfwidget.h"
#include "dragbutton.h"

RobotControlForm::RobotControlForm(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::RobotControlForm)
    ,m_pButtonGroup(new QButtonGroup(this))
    ,m_pTelemetryDlg(NULL)
{
    ui->setupUi(this);
    ui->tabWidget->tabBar()->setVisible(false);
    ui->tabWidget->setDocumentMode(true);
    m_pButtonGroup->setExclusive(true);  // 设置互斥
    m_pButtonGroup->addButton(ui->maual_btn,MANUAL_PAGE);
    m_pButtonGroup->addButton(ui->auto_btn,AUTO_PAGE);
    m_pButtonGroup->addButton(ui->teach_btn,TEACHING_PAGE);
    m_pButtonGroup->addButton(ui->remote_btn,REMOTE_OPERATION_PAGE);
    m_pButtonGroup->addButton(ui->set_btn,SET_PAGE);
    ui->auto_btn->setChecked(true);

    connect(m_pButtonGroup, static_cast<void (QButtonGroup::*)(QAbstractButton*)>(&QButtonGroup::buttonClicked), this, &RobotControlForm::onSwitchControl);
    connect(m_pButtonGroup,SIGNAL(buttonToggled(int,bool)), this, SLOT(onSwitchPage(int,bool)));
    connect(RobotList::getInstance(), &RobotList::curRobotChanged,this,[&](Robot * pCurRobot, Robot * pLastRobot){
        if(pLastRobot)
            disconnect(pLastRobot,NULL, this,NULL);
        if(pCurRobot)
        {
            onWarningChanged(pCurRobot->strWarning());
            connect(pCurRobot,&Robot::warningChanged, this, &RobotControlForm::onWarningChanged,Qt::UniqueConnection);
            connect(pCurRobot,SIGNAL(tempratureTooHighChanged(QList<QString>)), ui->auto_tab, SLOT(onShowTempratureWarn(QList<QString>)));
            connect(pCurRobot,&Robot::speakWSError,this,[=](){m_pSpeakBtn->setChecked(false);});
        }
    });

    m_pJointWidget =new JointDataDialog(this);
    m_pJointWidget->hide();
    setFixedSize(int(width() * g_xScale), int(height() * g_yScale));

    scaleWidgets(ui->title_widget,g_xScale,g_yScale);
    ui->control_widget->setFixedSize(width(),height() - ui->title_widget->height());

    // 创建可拖动按钮
    m_pSpeakBtn = new DragButton(this);
    m_pSpeakBtn->setGeometry(width()-200*g_xScale,400*g_yScale, 100*g_xScale, 100*g_xScale); // 设置按钮初始位置和大小
    m_pSpeakBtn->setCheckable(true);
    connect(m_pSpeakBtn,&QPushButton::toggled,this,&RobotControlForm::onAudioBtnChecked);
    m_pSpeakBtn->setStyleSheet("QPushButton{"
                                 "border-image: url(:/images/speak_close.png);"
                                 "background-color:transparent;"
                                 "}"
                                 "QPushButton:checked{"
                                 "border-image: url(:/images/speak_open.png);"
                                 "background-color:transparent;"
                                 "} ");
    m_pSpeakBtn->setText("");
    m_pSpeakBtn->setFocusPolicy(Qt::NoFocus);
}

void RobotControlForm::scaleWidgets(QWidget *widget, double xScale, double yScale)
{
    widget->setFixedSize(int(widget->width() * xScale), int(widget->height() * yScale));
    for (QWidget *child : widget->findChildren<QWidget*>()) {
        if(qobject_cast<QLabel*>(child)) //label需要拉伸，只改它的字号
        {
            QFont font = child->font();
            if(font.pixelSize()> 0)
                font.setPixelSize(int(font.pixelSize()*xScale));
            else if(font.pointSize()> 0)
                font.setPixelSize(int(font.pointSize()*xScale));
            child->setFont(font);
        }
        else
        {
            QRect geom = child->geometry();
            int width = qMax(1, static_cast<int>(int(geom.width() * xScale)));
            //当按钮高度比较大时使用y方向比例，当按钮比较小时使用x比例，防止按钮被压扁
            int height = qMax(1, static_cast<int>((geom.height() == geom.width() ? int(geom.height() * xScale) : int(geom.height() * yScale))));
            child->setFixedSize(width,height);
            //child->move(geom.left() * xScale,geom.top() * yScale);
            QFont font = child->font();
            if(font.pixelSize()> 0)
                font.setPixelSize(int(font.pixelSize()*xScale));
            else if(font.pointSize()> 0)
                font.setPixelSize(int(font.pointSize()*xScale));
            child->setFont(font);
        }
    }
}

RobotControlForm::~RobotControlForm()
{
    delete ui;
}

void RobotControlForm::on_about_btn_clicked()
{
    information(this,COMPANY_NAME+"\r\n"+WEBSITE+"\r\n"+SOFT_VERSION);
}


void RobotControlForm::on_exit_btn_clicked()
{
    if(question(this,tr("确定要退出程序吗？")) == 0)
    {
        Robot * pRobot = RobotList::getInstance()->getCurRobot();
        if(pRobot)
        {
            pRobot->disconnectRobot();
        }
        qApp->exit(0);
    }
}

void RobotControlForm::onSwitchControl(QAbstractButton *button)
{
    button->setChecked(true);
}

void RobotControlForm::onSwitchPage(int nID, bool b)
{
    if(b)
    {
        m_curTabType=nID;
        ui->tabWidget->setCurrentIndex(nID);
        Robot * pCurRobot = RobotList::getInstance()->getCurRobot();
        if(pCurRobot)
        {
            pCurRobot->setPage((TabType)nID);
        }
    }
}

void RobotControlForm::onWarningChanged(QString strWarning)
{
    ui->warning_label->setText(strWarning);
}


void RobotControlForm::on_goback_btn_clicked()
{
    if(question(this,tr("确定要断开当前机器人连接吗？")) == 0)
    {
        Robot * pRobot = RobotList::getInstance()->getCurRobot();
        if(pRobot)
        {
            pRobot->disconnectRobot();
        }
        emit gobackList();
    }
}

void RobotControlForm::updateData()
{
    //更新电源/使能状态
    Robot* pCurRobot=RobotList::getInstance()->getCurRobot();
    if(pCurRobot)
    {
        SportState hexData=  pCurRobot->SportStateData();
         ui->enable_state->setChecked(hexData.powerStat[3]);
        hexData.powerStat[0]? ui->charge->show():ui->charge->hide();
        ui->battery_widget->setBatteryLevel(hexData.batteryLevel);
    }
}

void RobotControlForm::showEvent(QShowEvent *event)
{
    Q_UNUSED(event);
    Robot* pCurRobot=RobotList::getInstance()->getCurRobot();
    if(pCurRobot)
    {
        connect(pCurRobot,&Robot::sportStateChanged, this, &RobotControlForm::updateData,Qt::UniqueConnection);
        if(pCurRobot->hasPerception())
        {
            ui->maual_btn->show();
            ui->teach_btn->show();
        }
        else
        {
            ui->maual_btn->hide();
            ui->teach_btn->hide();
        }
        if(pCurRobot->hasSpeak())
            m_pSpeakBtn->show();
        else
            m_pSpeakBtn->hide();
        if(pCurRobot->hasTelemetry())
            ui->telemetry_btn->show();
        else
            ui->telemetry_btn->hide();
        if(pCurRobot->hasZero())
            ui->zero_btn->show();
        else
            ui->zero_btn->hide();
    }
    ui->auto_btn->setChecked(true);
    onSwitchPage(AUTO_PAGE,true);//显示的时候发送切换自动界面
    QWidget::showEvent(event);
}

void RobotControlForm::hideEvent(QHideEvent *event)
{
    Q_UNUSED(event)
    m_pSpeakBtn->setChecked(false);
    if(m_pTelemetryDlg)
    {
        m_pTelemetryDlg->deleteLater();
        m_pTelemetryDlg = NULL;
    }
}

void RobotControlForm::resizeEvent(QResizeEvent *event)
{
    Q_UNUSED(event)
    if(m_pJointWidget)
         m_pJointWidget->setGeometry(0,ui->title_widget->height(),width(),height()-ui->title_widget->height());
}

void RobotControlForm::on_enable_btn_clicked()
{
    Robot* pCurRobot=RobotList::getInstance()->getCurRobot();
    if(pCurRobot)
    {
        pCurRobot->setEnable(true);
    }
}

void RobotControlForm::on_disable_btn_clicked()
{
    Robot* pCurRobot=RobotList::getInstance()->getCurRobot();
    if(pCurRobot)
    {
        pCurRobot->setEnable(false);
    }
}

void RobotControlForm::onAudioBtnChecked(bool bChecked)
{
    Robot* pCurRobot=RobotList::getInstance()->getCurRobot();
    if(pCurRobot)
    {
        if(bChecked)
        {
            //打开音频
            if(!pCurRobot->OpenSpeaker())
                warning(MainWindow::getInstance(),"打开语音设备失败！");
        }
        else
        {
            //关闭音频
            pCurRobot->closeSpeaker();
        }
    }

}

void RobotControlForm::on_pushButton_toggled(bool checked)
{
    if(checked)
    {
        m_pJointWidget->show();
        m_pJointWidget->raise();
    }
    else
        m_pJointWidget->hide();
}


void RobotControlForm::on_zero_btn_clicked()
{
    ZeroDialog dlg(MainWindow::getInstance());
    dlg.exec();
}


void RobotControlForm::on_telemetry_btn_clicked()
{
    if(m_pTelemetryDlg == NULL)
    {
        m_pTelemetryDlg = new TelemetryDialog(this);
        m_pTelemetryDlg->move(width() - m_pTelemetryDlg->width()-2,ui->title_widget->height()+2);
    }
    m_pTelemetryDlg->show();
}


